package com.lxnj.util;

import com.lxnj.model.po.TestPO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 响应结果工具类，返回的对象到浏览器会解析为json格式，需要有json相应的支持
 * 全部的返回结果都为map对象
 */
public class ResultUtil {

    Map<String,Object> result = new HashMap<>();

    private ResultUtil(){}

    private ResultUtil(String operationResult){
        result.put("operationResult", operationResult);
    }

    private ResultUtil(String operationResult, String failureMsg){
        result.put("operationResult", operationResult);
        result.put("failureMsg", failureMsg);
    }
    private ResultUtil(String operationResult, String failureMsg, Object responseList){
        result.put("operationResult", operationResult);
        result.put("failureMsg", failureMsg == null? "" : failureMsg);
        result.put("responseList", responseList == null? new ArrayList<>() : responseList);
    }

    public static ResultUtil build(){
        return new ResultUtil();
    }

    /**
     * 创建只有操作结果的响应
     * @param operationResult 操作结果
     * @return
     */
    public static ResultUtil build(String operationResult){
        return new ResultUtil(operationResult);
    }

    /**
     * 创建有操作结果和失败提示信息的响应
     * @param operationResult 操作结果
     * @param failureMsg 失败提示信息
     * @return
     */
    public static ResultUtil build(String operationResult, String failureMsg){
        return new ResultUtil(operationResult, failureMsg);
    }

    /**
     * 创建有操作结果和失败提示信息，还有响应数据列表的响应
     * @param operationResult 操作结果
     * @param failureMsg 失败提示信息
     * @param responseList 操作成功返回的对象，一般是数组格式
     * @return
     */
    public static ResultUtil build(String operationResult, String failureMsg, Object responseList){
        return new ResultUtil(operationResult, failureMsg, responseList);
    }

    /**
     * 如果上面参数不满足，可以使用该方法添加响应的返回
     * @param key 返回的键
     * @param value 返回的值
     * @return
     */
    public ResultUtil setProperties(String key, Object value){
        result.put(key,value);
        return this;
    }

    /**
     * 最终的返回结果
     * @return Map
     */
    public Map<String,Object> getResult(){
        return result;
    }

    public static void main(String[] args) {
        //返回成功响应
        System.out.println(ResultUtil.build("success","").getResult());
        //返回失败的响应
        System.out.println(ResultUtil.build("failure","没有这条记录").getResult());
        //返回成功，并有数据返回
        TestPO testPO = new TestPO();
        testPO.setTid(1);
        testPO.setName("李四");
        testPO.setType("type");
        List<TestPO> data = new ArrayList<>();
        data.add(testPO);
        data.add(testPO);
        System.out.println(ResultUtil.build("success","", data).getResult());
    }


}
